<template>

  <VipConfigOperation @add-vip-config="onAddVipConfig" @batch-remove="onBatchRemove"/>

  <Table border :columns="columns" :data="data" @on-selection-change="selection = $event">

    <template #status="{ row, index }">
      <DotTag type="primary" v-if="row.state">正常</DotTag>
      <DotTag type="error" v-else>失效</DotTag>
    </template>

    <template #expslot="{ row, index }">
      <DotTag type="primary" :dot="false" v-if="row.exp != -1">{{ row.exp }}</DotTag>
      <DotTag type="error" :dot="false" v-else>永久</DotTag>
    </template>

    <template #action="{ row, index }">
      <Button type="primary" icon="ios-create-outline" v-auth:svip:modify size="small" style="margin-right: 5px" @click="editConfig(row)">
        修改
      </Button>
      <Button type="error" v-auth:svip:remove icon="ios-remove-circle-outline" size="small" @click="remove(row, index)">移除</Button>
    </template>

  </Table>

  <VipConfigForm v-model="drawer" v-if="drawer.state" @refresh-data="querySVIPConfigs"/>

</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import DotTag from '../components/DotTag.vue'
import VipConfigOperation from '../components/user/VipConfigOperation.vue'
import VipConfigForm from '../components/user/VipConfigForm.vue';
import Tips from '../message';
import RSS from "../api/rssIndex.js";

const drawer = ref({title: "", state: false});

const columns = reactive([
  {
    type: "selection",
    width: 60
  },
  {
    title: "套餐名",
    key: "name",
  },
  {
    title: "套餐价格(CNY)",
    key: "price",
  },
  {
    title: "有效时间(天)",
    key: "exp",
    slot: "expslot"
  },
  {
    title: "赠送积分数量",
    key: "score",
  },
  {
    title: "状态",
    slot: "status",
  },
  {
    title: "操作",
    slot: "action",
    width: 180,
  },
]);

// 要修改 data, 可以通过 data.value = ...
const data = ref(reactive([]));

// 定义一个数据、存储复选框选中的所有元素
const selection = ref([]);

onMounted(querySVIPConfigs)

function querySVIPConfigs() {
  RSS.querySVIPConfigs().then(ret => {
    if (ret.status) {
      data.value = ret.list;
    }
  })
}

// 添加 Vip 套餐
function onAddVipConfig() {
  drawer.value.title = "添加套餐";
  drawer.value.state = true;
  drawer.value.row = {state: true}
}

// 批量删除
function onBatchRemove() {
  if (selection.value.length == 0) {
    Tips.warning("请至少选择一个需要删除的套餐数据");
    return;
  }
  // 获取要删除的所有ID 数据
  let ids = selection.value.map(s => s.id);
  Tips.confirm("您确定要删除选中的所有套餐吗?").then(() => {
    RSS.batchRemoveSvipConfig(ids).then(ret => {
      if (ret.status) {
        Tips.success(ret.message);
        querySVIPConfigs(); // 重新查询
      }
    })
  })
}

// 修改
function editConfig(row) {
  drawer.value.title = "修改套餐";
  drawer.value.state = true;
  drawer.value.row = {...row};
}

// 删除
function remove(row, index) {
  Tips.confirm("您确定要删除该套餐吗?").then(() => {
    RSS.removeSvipConfig(row.id).then(ret => {
      if (ret.status) {
        data.value.splice(index, 1);
        Tips.success(ret.message);
      }
    })
  })
}

</script>